package com.example.assetmanagement.aop;

import com.example.assetmanagement.domain.OperationLog;
import com.example.assetmanagement.service.OperationLogService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Component
@RequiredArgsConstructor
@Slf4j
public class OperationLogAspect {

    private final OperationLogService logService;
    private final HttpServletRequest request;

    @Pointcut("@annotation(com.example.assetmanagement.aop.Log)")
    public void logPointcut() {}

    @AfterReturning(value = "logPointcut() && @annotation(logAnno)")
    public void after(JoinPoint joinPoint, Log logAnno) {
        OperationLog logEntity = new OperationLog();
        // 此处可结合登录信息获取用户ID，此示例暂写 null
        logEntity.setUserId(null);
        logEntity.setModule(logAnno.module());
        logEntity.setOperationType(logAnno.operationType());
        String content = logAnno.content();
        if (content.isEmpty()) {
            content = joinPoint.getSignature().getName();
        }
        logEntity.setContent(content);
        logEntity.setIp(request.getRemoteAddr());
        logEntity.setCreatedAt(LocalDateTime.now());
        try {
            logService.add(logEntity);
        } catch (Exception e) {
            log.error("Failed to save operation log", e);
        }
    }
} 